package com.ling.zookeeper.zookeeperUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PingUtils {

	public static boolean pingServer(String ip) {
		BufferedReader br = null;
		int pingCount = 0;
		boolean pingFlag = false;
		try {
			Process p = Runtime.getRuntime().exec("ping -n 1 " + ip.split(":")[0]);
			br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while ((line = br.readLine()) != null) {
				sb.append(line + "\n");
				if (line.toUpperCase().contains("TTL")) {
					pingCount++;
				}
			}
			if (pingCount > 0) {
				pingFlag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return pingFlag;
	}

	public static boolean ipCheck(String text) {
		if (text != null && !text.isEmpty()) {
			String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
					+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
					+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d):[1-9]\\d+$";
			if (text.matches(regex)) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
	
	public static boolean pathCheck(String text) {
		if (text != null && !text.isEmpty()) {
			String regex = "^/([0-9a-zA-Z-_!@#$%^&*()+=]+/){0,}([0-9a-zA-Z-_!@#$%^&*()+=]+)?";
			if (text.matches(regex)) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
}
